package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"logi/cache"
	"logi/models"
	"strconv"
	"time"
)

/*
SELECT

	users.username AS Username,
	users.PASSWORD AS PASSWORD,
	user_roles.uid as Uid,
	user_roles.role_name as RoleName

FROM

	users
	LEFT JOIN user_roles ON users.id = user_roles.uid

WHERE

	user_roles.uid
*/
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var list []models.ListUserRole
	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("users").Select("users.username AS Username",
			"user_roles.uid as Uid",
			"user_roles.role_name as RoleName").Joins("LEFT JOIN user_roles ON users.id = user_roles.uid").Offset(offset).Limit(size).Debug().Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	var total int64
	models.DB.Model(list).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"data":  list,
		"msg":   "列表成功",
		"total": total,
	})
	return
}
